package vn.edu.thptduongbachmai.services;

import vn.edu.thptduongbachmai.common.ConcurrentLRUCache;
import vn.edu.thptduongbachmai.common.Configuration;
import vn.edu.thptduongbachmai.common.Utilities;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 *
 * @author tiennv4
 */
public class SessionService {

	
	private static ConcurrentLRUCache<String, Object> _session;
	public static SessionService Instance;

	static {
		Instance = new SessionService(Configuration.APP_MAXSIZE_SESSION);
	}

	private SessionService(int maxSize) {
		_session = new ConcurrentLRUCache<String, Object>(maxSize);
	}

	public String put(Object obj) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Calendar cal = Calendar.getInstance();
		String sid = Utilities.sha256(dateFormat.format(cal.getTime()));
		_session.put(sid, obj);
		return sid;
	}

	public Object get(String sid) {
		return _session.get(sid);
	}

	public boolean isValid(String sid) {
		if (_session.containsKey(sid)) {
			return true;
		}
		return false;
	}

	public boolean remove(String sid) {
		if (!_session.containsKey(sid)) {
			return false;
		}
		_session.remove(sid);
		return true;
	}
}